<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * 代理商
 *
 * @icon fa fa-circle-o
 */
class Agent extends Backend
{
 
	protected $relationSearch = true;
	
    /**
     * Agent模型对象
     * @var \app\common\model\Agent
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Agent;
        $arr = [
	        'statusList' =>  \app\common\model\Agent::$statusList,
	        'levelList' => \app\common\model\Agent::$levelList
        ];
		$this->assign($arr);
		$this->assignconfig($arr);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
	
	
	
	/**
	 * 查看
	 */
	public function index()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isAjax()) {
			//如果发送的来源是Selectpage，则转发到Selectpage
			if ($this->request->request('keyField')) {
				return $this->selectpage();
			}
			list($where, $sort, $order, $offset, $limit) = $this->buildparams();
			
			
			$with = ['user', 'puser', 'ppuser'];
			
			$total = $this->model
				->with($with)
				->where($where)
				->order($sort, $order)
				->count();
			
			$list = $this->model
				->with($with)
				->where($where)
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
			
			$list = collection($list)->toArray();
			$result = array("total" => $total, "rows" => $list);
			
			return json($result);
		}
		return $this->view->fetch();
	}
	
	
	/**
	 * 添加
	 */
	public function add()
	{
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			if ($params) {
				if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
					$params[$this->dataLimitField] = $this->auth->id;
				}
				
				$user = Db::name('user')
					->where(['mobile' => $params['mobile']])
					->find();
				
				!$user && $this->error('用户不存在');
				
				$row = $this->model->where(['user_id' => $user['id']])->find();
				$row && $this->error('该用户已经是代理商');
				
				$params['user_id'] = $user['id'];
				if($params['level'] != \app\common\model\Agent::LEVEL_4) {
					!$params['pmobile'] && $this->error('上级代理不能为空');
					$puser = Db::name('user')->alias('u')
						->join('agent a', 'u.id = a.user_id', 'left')
						->where(['u.mobile' => $params['pmobile']])
						->field('a.*')
						->find();
					!$puser && $this->error('上级代理不存在');
					
//					if($puser['level'] - $params['level'] != 1){
//						$this->error('不能越级设置代理');
//					}
					
					//给初级设置上级为高级
					if($puser['level'] == \app\common\model\Agent::LEVEL_4 && $params['level'] == \app\common\model\Agent::LEVEL_2) {
						$params['ppid']	 = $puser['user_id'];
					} else {
						
						$params['pid'] = $puser['user_id'];
						$params['ppid'] = $puser['pid'];
					}
					
				}
				
				
				Db::startTrans();
				try {
					//是否采用模型验证
					if ($this->modelValidate) {
						$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
						$this->model->validate($validate);
					}
					$result = $this->model->allowField(true)->save($params);
					if (!$result) {
						$this->error($this->model->getError());
					}
					
					if($params['level'] != $user['level']) {
						//更改用户等级
						$userRes = Db::name('user')
							->where(['id' => $user['id']])
							->setField('level', $params['level']);
						if(!$userRes) {
							throw new Exception('更改用户等级出错');
						}
						
						//记录会员等级更改记录
						$logModel = new \app\common\model\UserLevelRecord();
						$logRes = $logModel->addRecord($user['id'], $user['level'], $params['level'], '', '后台更改等级');
						if(!$logRes) {
							throw new Exception('记录等级变更记录出错');
						}
						
					}
					Db::commit();
					$this->success();
				} catch (\think\exception\PDOException $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		return $this->view->fetch('edit', [
			'row' => [
				'level' => \app\common\model\Agent::LEVEL_2,
				'status' => \app\common\model\Agent::STATUS_Y,
			]
		]);
	}
	
	/**
	 * 编辑
	 */
	public function edit($ids = NULL)
	{
		$row = $this->model->get($ids);
		if (!$row)
			$this->error(__('No Results were found'));
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds)) {
			if (!in_array($row[$this->dataLimitField], $adminIds)) {
				$this->error(__('You have no permission'));
			}
		}
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			if ($params) {
				$user = Db::name('user')
					->where(['mobile' => $params['mobile']])
					->find();
				
				!$user && $this->error('用户不存在');
				
				$agent = $this->model->where(['user_id' => $user['id'], 'id' => ['neq', $ids]])->find();
				$agent && $this->error('该用户已经是代理商');
				
				$params['user_id'] = $user['id'];
				if($params['level'] != \app\common\model\Agent::LEVEL_4) {
					!$params['pmobile'] && $this->error('上级代理不能为空');
					$puser = Db::name('user')->alias('u')
						->join('agent a', 'u.id = a.user_id', 'left')
						->where(['u.mobile' => $params['pmobile']])
						->field('a.*')
						->find();
					!$puser && $this->error('上级代理不存在');
					
					if($puser['level'] - $params['level'] != 1){
						$this->error('不能越级设置代理');
					}
					
					$params['pid'] = $puser['user_id'];
					$params['ppid'] = $puser['pid'];
				} else {
					$params['pid'] = '';
					$params['ppid'] = '';
				}
				
				
				Db::startTrans();
				try {
					//是否采用模型验证
					if ($this->modelValidate) {
						$name = basename(str_replace('\\', '/', get_class($this->model)));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
						$row->validate($validate);
					}
					$result = $row->allowField(true)->save($params);
					if (!$result) {
						$this->error($row->getError());
					}
					
					
					if($params['level'] != $row['level']) {
						//更改用户等级
						$userRes = Db::name('user')
							->where(['id' => $user['id']])
							->setField('level', $params['level']);
						if(!$userRes) {
							throw new Exception('更改用户等级出错');
						}
						
						//记录会员等级更改记录
						$logModel = new \app\common\model\UserLevelRecord();
						$logRes = $logModel->addRecord($user['id'], $row['level'], $params['level'], '', '后台更改等级');
						if(!$logRes) {
							throw new Exception('记录等级变更记录出错');
						}
						
					}
					
					
					Db::commit();
					$this->success();
				} catch (\think\exception\PDOException $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}
	
}
